package com.lanou.connotationjoke.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.connotationjoke.view.NewListView;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.view.RefreshableView;
import com.lanou.connotationjoke.adapter.HomeRecommendationListVIewAdapter;
import com.lanou.connotationjoke.db.HomeRecommendationEntity;
import com.lanou.connotationjoke.db.HomeRecommendationEntityDao;
import com.lanou.connotationjoke.entity.AppUrl;
import com.lanou.connotationjoke.entity.CurrentItemEty;
import com.lanou.connotationjoke.entity.DataDetialEty;
import com.lanou.connotationjoke.entity.GroupEty;
import com.lanou.connotationjoke.entity.JsonEty;
import com.lanou.connotationjoke.entity.LargeImageEty;
import com.lanou.connotationjoke.entity.UserEty;
import com.lanou.connotationjoke.tool.DaoSingleton;
import com.lanou.connotationjoke.tool.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by dllo on 16/1/8.
 */
public class HomeRecommendationFragment extends BaseFragment{
    private RefreshableView refreshableView;
    private NewListView listView;
    private HomeRecommendationListVIewAdapter adapter;
    private final String URL = AppUrl.HOMERECOMMENDATION;
    private List<DataDetialEty> datas;
    private HomeRecommendationEntityDao recommendationEntityDao =
            DaoSingleton.getInstance().getHomeRecommendationEntityDao();
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            EventBus.getDefault().post("stop");
            return false;

        }
    });
    private static boolean isRegister = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_recommendation,null);
        refreshableView = (RefreshableView) view.findViewById(R.id.refresh);
        listView = (NewListView) view.findViewById(R.id.listview_home_recommendation);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isRegister == false){
            EventBus.getDefault().register(this);
            isRegister = true;
        }
        VolleySingleton.addRequest(URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                JsonEty jsonEty = gson.fromJson(response, JsonEty.class);
                if (null != jsonEty&&null != jsonEty.getData()){
                    datas = jsonEty.getData().getData();
                }
                adapter = new HomeRecommendationListVIewAdapter(getActivity(), datas);
                listView.setAdapter(adapter);
                insertOrReplaceToHomeRecommendationEntityDao(jsonEty);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                datas = getDataFromHomeRecommendationEntityDao();
                adapter = new HomeRecommendationListVIewAdapter(getActivity(), datas);
                listView.setAdapter(adapter);
            }
        });

        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                VolleySingleton.addRequest(URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        JsonEty jsonEty = gson.fromJson(response, JsonEty.class);
                        datas = jsonEty.getData().getData();
                        adapter.refreshData(datas);
                        refreshableView.finishRefreshing();
                        insertOrReplaceToHomeRecommendationEntityDao(jsonEty);
                        handler.sendEmptyMessage(0);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        refreshableView.finishRefreshing();
                        handler.sendEmptyMessage(0);
                    }
                });
            }
        }, 4);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isRegister = false;
    }

    /**
     *
     * @param currentItemEty
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(CurrentItemEty currentItemEty) {
        if (currentItemEty.getI() == 0){
            listView.setSelection(0);
            new Thread() {
                @Override
                public void run() {
                    final long downTime = SystemClock.currentThreadTimeMillis();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent down = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_DOWN, 10, 300, 0);
                            listView.dispatchTouchEvent(down);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 700, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 1000, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });

                    SystemClock.sleep(1000);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent up = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_UP, 10, 1000, 0);
                            listView.dispatchTouchEvent(up);
                        }
                    });
                }
            }.start();


        }

    }








    private void insertOrReplaceToHomeRecommendationEntityDao(JsonEty jsonEty){
        recommendationEntityDao.deleteAll();
        List<DataDetialEty> datas = jsonEty.getData().getData();

        for (DataDetialEty dataDetialEty:datas){
            if (dataDetialEty.getGroup()!=null) {
                String avatar_url = dataDetialEty.getGroup().getUser().getAvatar_url();
                String name = dataDetialEty.getGroup().getUser().getName();
                String content = dataDetialEty.getGroup().getContent();
                String category_name = dataDetialEty.getGroup().getCategory_name();
                int digg_count = dataDetialEty.getGroup().getDigg_count();
                int bury_count = dataDetialEty.getGroup().getBury_count();
                int comment_count = dataDetialEty.getGroup().getComment_count();
                int share_count = dataDetialEty.getGroup().getShare_count();
                String share_url = dataDetialEty.getGroup().getShare_url();
                String uri = null;
                if (null != dataDetialEty.getGroup().getLarge_image()){
                    uri = dataDetialEty.getGroup().getLarge_image().getUri();
                }

                String coverImageUri = dataDetialEty.getGroup().getCover_image_uri();
                String mp4Url = dataDetialEty.getGroup().getMp4_url();
                int playCount = dataDetialEty.getGroup().getPlay_count();
                recommendationEntityDao.insert(new HomeRecommendationEntity(recommendationEntityDao.count(),avatar_url,name,content
                        ,category_name,uri,coverImageUri,mp4Url,playCount,digg_count,bury_count
                        ,comment_count,share_count,share_url));
            }
        }
    }


    private List<DataDetialEty> getDataFromHomeRecommendationEntityDao(){
        List<DataDetialEty> datas = new ArrayList<>();
        List<HomeRecommendationEntity> homeRecommendationEntities = recommendationEntityDao.queryBuilder().list();
        for (HomeRecommendationEntity homeRecommendationEntity:homeRecommendationEntities){
            DataDetialEty dataDetialEty = new DataDetialEty();
            GroupEty groupEty = new GroupEty();
            UserEty userEty = new UserEty();
            userEty.setAvatar_url(homeRecommendationEntity.getAvatar_url());
            userEty.setName(homeRecommendationEntity.getName());
            groupEty.setUser(userEty);
            groupEty.setContent(homeRecommendationEntity.getContent());
            groupEty.setCategory_name(homeRecommendationEntity.getCategory_name());
            groupEty.setDigg_count(homeRecommendationEntity.getDigg_count());
            groupEty.setBury_count(homeRecommendationEntity.getBury_count());
            groupEty.setComment_count(homeRecommendationEntity.getComment_count());
            groupEty.setShare_count(homeRecommendationEntity.getShare_count());
            groupEty.setShare_url(homeRecommendationEntity.getShare_url());
            if (homeRecommendationEntity.getUri()!=null){
                LargeImageEty largeImageEty = new LargeImageEty();
                largeImageEty.setUri(homeRecommendationEntity.getUri());
                groupEty.setLarge_image(largeImageEty);
            }
            groupEty.setCover_image_uri(homeRecommendationEntity.getCover_image_uri());
            groupEty.setMp4_url(homeRecommendationEntity.getMp4_url());
            dataDetialEty.setGroup(groupEty);
            groupEty.setPlay_count(homeRecommendationEntity.getPlay_count());
            datas.add(dataDetialEty);
        }
        return datas;
    }



}
